package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

func main() {
	testClientPost()
}
func testClientPost() {
	//创建客户端
	client := http.Client{}
	//构建参数
	contentType := "application/json;charset=utf-8"

	type LoginInfo struct {
		Username string `json:"username"`
		Password string `json:"Password"`
	}
	login := LoginInfo{Username: "zhb", Password: "123"}
	info, err := json.Marshal(login)
	if err != nil {
		log.Println("json format error:", err)
		return
	}

	body := bytes.NewBuffer(info)
	response, err := client.Post("http://127.0.0.1:9090/login", contentType, body)

	CheckErr32(err)
	fmt.Printf("响应状态码: %v\n", response.StatusCode)
	if response.StatusCode == 200 {
		defer response.Body.Close()
		fmt.Println("网络请求成功")

		//处理
		data, err := io.ReadAll(response.Body)
		CheckErr32(err)
		fmt.Println(string(data))
	}
}

// 检查错误
func CheckErr32(err error) {
	defer func() {
		if ins, ok := recover().(error); ok {
			fmt.Println("程序出现异常：", ins.Error())
		}
	}()
	if err != nil {
		panic(err)
	}
}
